<template>
  <div class="tool-item flex gap-4 overflow-hidden tool-dom"
    :data-handle="toolsData.handle"
    :data-advertisement_id="toolsData.advertisement_id ? toolsData.advertisement_id : ''"
    :data-position="toolPosition"
    :data-index="toolPosIndex">
    <common-link path="/tool/:handle"
      @click.native="handleExp(0, toolsData)"
      target="_blank"
      :params="{ handle: toolsData.handle}"
      class="flex-shrink-0 tool-linear go-tool-detail-pic overflow-hidden">
      <div class="flex tool-pic items-center justify-center skeleton-bg border border-gray-2000 rounded"
        ref="imgBox">
        <common-image class="w-full h-full flex-shrink-0"
          :src="toolsData.image"
          :alt="toolName"></common-image>
      </div>
    </common-link>
    <div class="flex-1 w-0">
      <div class="relative fs0 max-w-full">
        <common-link path="/tool/:handle"
          @click.native="handleExp(1, toolsData)"
          target="_blank"
          :params="{ handle: toolsData.handle}"
          :title="toolName"
          class="max-w-full inline-block go-tool-detail-name text-xl font-semibold text-gray-1000 truncate break-words hover:text-purple-1300">
          {{ toolName }}
        </common-link>
      </div>
      <div class="mt-1 text-base text-gray-1500 break-words truncate leading-7 go-tool-detail-description"
        :title="toolsData.description">
        {{toolsData.description}}
      </div>
      <div class="flex-shrink-0 flex items-center justify-between mt-3">
        <div class="flex-1 flex items-center">
          <div class="flex-shrink-0 flex items-center"
            :title="$t('monthlyVisits')">
            <svg-icon className="text-base mt--3"
              iconName='similarweb'></svg-icon>
            <span class="ml-1.5 text-base text-gray-1000">{{toolsData.month_visited_count | vResetVisit}}</span>
          </div>

          <div class="flex-shrink-0 flex items-center flag ml-4"
            v-if="toolsData.traffic && (toolsData.traffic.top_region || toolsData.traffic.top_region_value)"
            :title="getTitle()">
            <img :src="getImage(toolsData.traffic.top_region)"
              alt=""
              srcset=""
              v-if="toolsData.traffic.top_region">
            <span class="text-base text-gray-1000 ml-1.5"
              v-if="toolsData.traffic.top_region_value">{{(toolsData.traffic.top_region_value * 100).toFixed(2)}}%</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mixinsExposure from '~/mixins/mixins-exposure'
import { mapActions, mapState } from 'vuex'
export default {
  name: 'MinTools',
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      countries: (state) => state.countries,
    }),
    toolName() {
      return this.$websiteName(this.toolsData)
    },
  },
  props: {
    toolsData: {
      type: Object,
      default: {},
    },
    toolPosition: {
      type: String,
      default: '',
    },
    toolPosIndex: {
      type: Number,
      default: 1,
    },
  },
  mixins: [mixinsExposure],
  data() {
    return {
      loading: false,
    }
  },
  //TODO
  watch: {
    toolsData: {
      handler() {
        if (this.toolsData && this.toolsData.image) {
          let iSrc = this.toolsData.image
          if (iSrc.indexOf('x-oss-process') === -1) {
            iSrc = `${iSrc}${
              iSrc.indexOf('?') === -1 ? '?' : '&'
            }x-oss-process=image/resize,l_600,m_lfit`
          }
          if (
            iSrc.indexOf('https://nav-station.oss-accelerate.aliyuncs.com') >= 0
          ) {
            iSrc = iSrc.replace(
              'https://nav-station.oss-accelerate.aliyuncs.com',
              'https://cdn-images.toolify.ai'
            )
          }
          this.toolsData.image = iSrc
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val ? val : 0
      }
    },
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
  },
  methods: {
    ...mapActions(['exposure']),
    resetPath(tHandle, cHandle) {
      let query = {}
      query.attributes = `${tHandle}-${cHandle}`
      return query
    },
    async addOrCancleFavorites() {
      this.loading = true
      try {
        try {
          let res

          switch (this.toolsData.user_collected) {
            case 0:
              res = await this.$axiosApi.postFavorites({
                handle: this.toolsData.handle,
              })
              break
            case 1:
              res = await this.$axiosApi.deleteFavorites({
                handle: this.toolsData.handle,
              })
              break
            default:
              console.log('error')
          }

          this.loading = false
          if (res && res.code === 200) {
            this.$message.success(
              this.toolsData.user_collected
                ? this.$i18n.t('cancelFavoritesSuccess')
                : this.$i18n.t('addFavoritesSuccess')
            )
            this.toolsData.collected_count = this.toolsData.user_collected
              ? parseInt(this.toolsData.collected_count) - 1
              : parseInt(this.toolsData.collected_count) + 1
            this.toolsData.user_collected = this.toolsData.user_collected
              ? 0
              : 1

            this.$emit('updateData', this.toolsData.handle)
          }
        } catch (error) {
          this.loading = false
          console.log(error)
        }
      } catch (error) {}
    },
    //判断是否有国旗
    getImage(name) {
      try {
        const image = require('@/static/images/flags/' + name + '.png')
        if (image) {
          return image
        } else {
          return ''
        }
      } catch (error) {
        //console.log(error)
      }
    },
    getWidth(item) {
      let total = this.toolsData.traffic.top_traffic_sources.reduce(
        (total, titem) => {
          return total + titem.value
        },
        0
      )
      return {
        width: `${((item.value / total) * 100).toFixed(2)}%`,
      }
    },
    getTitle() {
      let targetCountry = this.countries.find((item) => {
        return item.value === this.toolsData.traffic.top_region
      })
      let percent = `${(this.toolsData.traffic.top_region_value * 100).toFixed(
        2
      )}%`

      return `${
        targetCountry && targetCountry.label
          ? targetCountry.label
          : this.toolsData.traffic.top_region
      }: ${percent}`
    },
    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },
    handleExp(key = 0, toolsData) {
      this.getThrottledClickFunction(toolsData, key)()
    },
    getThrottledClickFunction(toolsData, key) {
      let functionKey = `${toolsData.handle}-${key}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exporeData = this.getExporeData(
            toolsData,
            this.toolPosition,
            this.toolPosIndex,
            this.isSearch
          )
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
  },
}
</script>
<style lang='scss' scoped>
.tool-item {
  .tool-linear {
    .tool-pic {
      overflow: hidden;
      width: 150px;
      height: 100px;
    }
  }

  .flag {
    margin-top: -1px;
    img {
      width: 17px;
      height: 12px;
    }
  }
}
</style>
